package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exceptions.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {
    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private ApartmentFacilityService apartmentFacilityService;
    @Autowired
    private ApartmentLabelService apartmentLabelService;
    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;

    @Autowired
    private ProvinceInfoService provinceInfoService;

    @Autowired
    private CityInfoService cityInfoService;

    @Autowired
    private DistrictInfoService districtInfoService;


    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;

    @Autowired
    private FacilityInfoMapper facilityInfoMapper;

    @Autowired
    private LabelInfoMapper labelInfoMapper;

    @Autowired
    private FeeValueMapper feeValueMapper;

    @Autowired
    private GraphInfoMapper graphInfoMapper;

    @Autowired
    private RoomInfoService roomInfoService;
    /**
     * 实现步骤：
     *     1. 接收整合数据vo
     *     2. 判定是否是修改
     *     3. 调用公寓的保存或者更新
     *     4. 如果是更新，删除中间的四个表的数据
     *     5. 最终一定进行中间表的数据批量保存
     * @param apartmentSubmitVo
     */
    @Override
    public void customerSaveOrUpdate(ApartmentSubmitVo apartmentSubmitVo) {
        // 1. 判定是否是修改 注意：saveOrUpdate之前
        boolean isUpdate = apartmentSubmitVo.getId() != null;

        // 设置省市区的名称
        apartmentSubmitVo.setProvinceName(provinceInfoService.getById(apartmentSubmitVo.getProvinceId()).getName());
        apartmentSubmitVo.setCityName(cityInfoService.getById(apartmentSubmitVo.getCityId()).getName());
        apartmentSubmitVo.setDistrictName(districtInfoService.getById(apartmentSubmitVo.getDistrictId()).getName());


        // 2. 调用公寓的保存或者更新
        saveOrUpdate(apartmentSubmitVo);//多态

        // 3. 如果是更新，删除中间的四个表的数据
        if (isUpdate){
            //3.1 图片表 item_id 公寓或者房间id + item_type等于公寓或者房间类型
            LambdaQueryWrapper<GraphInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(GraphInfo::getItemId , apartmentSubmitVo.getId());
            lambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
            graphInfoService.remove(lambdaQueryWrapper);
            //3.2 配套中间表
            LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId,apartmentSubmitVo.getId());
            apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);
            //3.3 标签中间表
            LambdaQueryWrapper<ApartmentLabel> apartmentLabelLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apartmentLabelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId,apartmentSubmitVo.getId());
            apartmentLabelService.remove(apartmentLabelLambdaQueryWrapper);
            //3.4 杂费中间表
            LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId,apartmentSubmitVo.getId());
            apartmentFeeValueService.remove(apartmentFeeValueLambdaQueryWrapper);
        }
        // 4. 最终一定要进行中间表的数据的保存
        // 4.1 图片信息
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
        if (!CollectionUtils.isEmpty(graphVoList)){
            List<GraphInfo> graphInfoList = new ArrayList<>(graphVoList.size());
            for(GraphInfo graphVo : graphInfoList){
                GraphInfo graphInfo  = new GraphInfo();
                graphInfo.setName(graphVo.getName());
                graphInfo.setUrl(graphVo.getUrl());
                graphInfo.setItemId(apartmentSubmitVo.getId());
                graphInfo.setItemType(ItemType.APARTMENT);
                graphInfoList.add(graphInfo);
            }
            graphInfoService.saveBatch(graphInfoList);
        }

        // 4.2 公寓配套
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
        if (!CollectionUtils.isEmpty(facilityInfoIds)){
            List<ApartmentFacility> apartmentFacilityList = new ArrayList<>(facilityInfoIds.size());
            for (Long facilityInfoId: facilityInfoIds) {
                ApartmentFacility apartmentFacility = ApartmentFacility.builder().facilityId(facilityInfoId).apartmentId(apartmentSubmitVo.getId()).build();
                apartmentFacilityList.add(apartmentFacility);
            }
            apartmentFacilityService.saveBatch(apartmentFacilityList);
        }

        // 4.3 公寓标签
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();
        if (!CollectionUtils.isEmpty(labelIds)){
            List<ApartmentLabel> apartmentLabels = new ArrayList<>(labelIds.size());
            for (Long labelId : labelIds) {
                ApartmentLabel apartmentLabel = ApartmentLabel.builder().labelId(labelId).apartmentId(apartmentSubmitVo.getId()).build();
                apartmentLabels.add(apartmentLabel);
            }
            apartmentLabelService.saveBatch(apartmentLabels);
        }

        // 4.4 杂费表
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
        if (!CollectionUtils.isEmpty(feeValueIds)){
            List<ApartmentFeeValue> apartmentFeeValues = new ArrayList<>(feeValueIds.size());
            for (Long feeValueId : feeValueIds) {
                ApartmentFeeValue apartmentFeeValue = ApartmentFeeValue.builder().feeValueId(feeValueId).apartmentId(apartmentSubmitVo.getId()).build();
                apartmentFeeValues.add(apartmentFeeValue);
            }
            apartmentFeeValueService.saveBatch(apartmentFeeValues);
        }
    }


    @Override
    public void customPage(Page<ApartmentItemVo> apartmentItemVoPage, ApartmentQueryVo queryVo) {
        apartmentInfoMapper.customSelectPage(apartmentItemVoPage,queryVo);
    }

    @Override
    public ApartmentDetailVo queryDetail(Long id) {
        //1. id查询公寓信息详情
        ApartmentInfo apartmentInfo = getById(id);


        //2. 公寓id查询配套信息(推荐直接调用配套的mapper，少一层service的方法)
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.queryByApartmentId(id);
        //3. 公寓id查询图片集合
        List<GraphVo> graphVoList = graphInfoMapper.queryByItemId(id,ItemType.APARTMENT);
        //4. 根据公寓id查询标签集合
        List<LabelInfo> labelInfoList = labelInfoMapper.queryByApartmentId(id);
        //5. 公寓id查询杂费想和杂费明集合
        List<FeeValueVo> feeValueVoList = feeValueMapper.queryByApartmentId(id);
        //6. 合并到ApartmentDetailVo对象返回即可
        ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();

        apartmentDetailVo.setFacilityInfoList(facilityInfoList);
        apartmentDetailVo.setGraphVoList(graphVoList);
        apartmentDetailVo.setFeeValueVoList(feeValueVoList);
        apartmentDetailVo.setLabelInfoList(labelInfoList);

        //将原对象的属性值给目标对象的相同属性！ 属性值迁移
        BeanUtils.copyProperties(apartmentInfo,apartmentDetailVo);
        return apartmentDetailVo;
    }

    /**
     * 1. 根据id删除公寓
     * 2. 删除中间表的数据 (图片 | item_type item_id | apartment_id)
     * @param id
     */
    @Override
    public void customRemoveById(Long id) {
        //1. 判定公寓是否存在房间
        LambdaQueryWrapper<RoomInfo> roomInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roomInfoLambdaQueryWrapper.eq(RoomInfo::getApartmentId,id);
        long count = roomInfoService.count(roomInfoLambdaQueryWrapper);
        if (count > 0){
            //不能继续执行了！返回删除失败的提示
            //方案1：自定义各种类型的异常 例如：删除公寓失败的异常 账号错误的异常 密码错误异常...[不推荐]
            //问题：定义很多很多异常，很多很多的处理器，返回不同的状态码以及message
            //方案2：自定义通用异常，异常中可以携带code | message，捕捉以后直接获取code message -> Result
            // 只需定义一个异常(code | message) || 写一个处理方法
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR.getCode(),ResultCodeEnum.DELETE_ERROR.getMessage());
        }

        //2. 根据id删除公寓
        removeById(id);
        //3. 删除中间表的数据(图片 | item_type item_id | apartment_id)
        //图片
        LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId,id);
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType,ItemType.APARTMENT);
        graphInfoService.remove(graphInfoLambdaQueryWrapper);

        //公寓标签
        LambdaQueryWrapper<ApartmentLabel> apartmentLabelLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentLabelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId,id);
        apartmentLabelService.remove(apartmentLabelLambdaQueryWrapper);

        //公寓配套
        LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId,id);
        apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);

        //公寓杂费
        LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId,id);
        apartmentFeeValueService.remove(apartmentFeeValueLambdaQueryWrapper);

    }
}




